package csc.fresher.finalgroupfour.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import csc.fresher.finalgroupfour.dao.UserDAO;
import csc.fresher.finalgroupfour.domain.Role;
import csc.fresher.finalgroupfour.domain.User;

@Service
public class UserService {
	@Autowired
	private UserDAO userDAO;
	
	@Autowired
	private RoleService roleService;

	public void addUser(User user) {
		userDAO.addUser(user);
	}

	public List<User> listUsers() {
		return userDAO.listUsers();
	}

	public void updateUser(User user) {
		userDAO.updateUser(user);
	}

	public void deleteUser(User user) {
		userDAO.deleteUser(user);
	}

	public User findUser(String loginId) {
		return userDAO.findUser(loginId);
	}
	
	public List<User> listNormalUsers() {
		return userDAO.listNormalUsers();
	}

	public String getLoginId() {
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		return auth.getName();
	}

	public void changeUserState(User user) {
		if (user.getUserState().equalsIgnoreCase("enabled")) {
			user.setUserState("disabled");
		} else if (user.getUserState().equalsIgnoreCase("disabled")) {
			user.setUserState("enabled");
		}
		user.setAttemptedLogin(0);
		updateUser(user);
	}

	public User createUser(String loginId, String password, String userState) {
		// Create User instance from user input parameters.
		User user = new User(loginId, password, userState);
		// Set default Role for every new User is ROLE_USER
		Role role = roleService.findRole("ROLE_USER");
		user.setRole(role);
		user.setAttemptedLogin(0);
		addUser(user);
		return user;
	}
}
